<template>
  <div class="posts-management">
    <div class="page-header">
      <h2>帖子管理</h2>
      <div class="header-actions">
        <el-select
          v-model="filters.admin_status"
          placeholder="审核状态"
          clearable
          style="width: 120px; margin-right: 10px"
          @change="fetchPosts"
        >
          <el-option label="待审核" value="pending" />
          <el-option label="已通过" value="approved" />
          <el-option label="已拒绝" value="rejected" />
        </el-select>

        <el-select
          v-model="filters.post_status"
          placeholder="帖子状态"
          clearable
          style="width: 120px; margin-right: 10px"
          @change="fetchPosts"
        >
          <el-option label="寻找中" value="searching" />
          <el-option label="已找到" value="found" />
          <el-option label="已关闭" value="closed" />
        </el-select>

        <el-button @click="fetchPosts" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-card>
      <el-table
        :data="posts"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column label="宠物信息" width="200">
          <template #default="{ row }">
            <div class="pet-info">
              <img
                v-if="row.pet.photo_url"
                :src="getFullImageUrl(row.pet.photo_url)"
                class="pet-photo"
                alt="宠物照片"
              />
              <div>
                <div class="pet-name">{{ row.pet.name || '未命名' }}</div>
                <div class="pet-details">
                  {{ row.pet.species }} · {{ row.pet.color }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="last_seen_location" label="最后目击地点" width="150" />

        <el-table-column label="发布者" width="120">
          <template #default="{ row }">
            {{ row.owner.username }}
          </template>
        </el-table-column>

        <el-table-column label="帖子状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getPostStatusType(row.post_status)"
            >
              {{ getPostStatusText(row.post_status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getAdminStatusType(row.admin_status)"
            >
              {{ getAdminStatusText(row.admin_status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="线索数" width="80">
          <template #default="{ row }">
            <el-tag type="info">{{ row.sightings_count }}</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="发布时间" width="120">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewPost(row)">
              查看详情
            </el-button>
            <el-dropdown @command="(command: string) => handleCommand(command, row)">
              <el-button size="small" type="primary">
                更多操作
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit">编辑帖子</el-dropdown-item>
                  <el-dropdown-item
                    command="approve"
                    v-if="row.admin_status === 'pending'"
                  >
                    审核通过
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="reject"
                    v-if="row.admin_status === 'pending'"
                  >
                    审核拒绝
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <span style="color: #f56c6c">删除帖子</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="帖子详情"
      width="800px"
    >
      <div v-if="selectedPost" class="post-detail">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="detail-section">
              <h4>宠物信息</h4>
              <div class="pet-detail">
                <img
                  v-if="selectedPost.pet.photo_url"
                  :src="getFullImageUrl(selectedPost.pet.photo_url)"
                  class="pet-detail-photo"
                  alt="宠物照片"
                />
                <div class="pet-detail-info">
                  <p><strong>名字：</strong>{{ selectedPost.pet.name || '未命名' }}</p>
                  <p><strong>品种：</strong>{{ selectedPost.pet.species }} - {{ selectedPost.pet.breed }}</p>
                  <p><strong>颜色：</strong>{{ selectedPost.pet.color }}</p>
                  <p><strong>性别：</strong>{{ selectedPost.pet.gender === 'male' ? '雄性' : '雌性' }}</p>
                  <p v-if="selectedPost.pet.description"><strong>描述：</strong>{{ selectedPost.pet.description }}</p>
                </div>
              </div>
            </div>
          </el-col>

          <el-col :span="12">
            <div class="detail-section">
              <h4>走失信息</h4>
              <p><strong>最后目击地点：</strong>{{ selectedPost.last_seen_location }}</p>
              <p><strong>最后目击时间：</strong>{{ formatDate(selectedPost.last_seen_time) }}</p>
              <p><strong>联系方式：</strong>{{ selectedPost.contact_info || '未提供' }}</p>
              <p><strong>发布者：</strong>{{ selectedPost.owner.username }}</p>
              <p><strong>发布时间：</strong>{{ formatDate(selectedPost.created_at) }}</p>
              <p><strong>帖子状态：</strong>
                <el-tag :type="getPostStatusType(selectedPost.post_status)">
                  {{ getPostStatusText(selectedPost.post_status) }}
                </el-tag>
              </p>
              <p><strong>审核状态：</strong>
                <el-tag :type="getAdminStatusType(selectedPost.admin_status)">
                  {{ getAdminStatusText(selectedPost.admin_status) }}
                </el-tag>
              </p>
            </div>
          </el-col>
        </el-row>
      </div>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 帖子编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑帖子"
      width="800px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <h4>走失信息</h4>
            <el-form-item label="最后目击地点" prop="last_seen_location">
              <el-input v-model="editForm.last_seen_location" />
            </el-form-item>
            <el-form-item label="最后目击时间" prop="last_seen_time">
              <el-date-picker
                v-model="editForm.last_seen_time"
                type="datetime"
                placeholder="选择日期时间"
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="联系方式" prop="contact_info">
              <el-input v-model="editForm.contact_info" />
            </el-form-item>
            <el-form-item label="视频链接" prop="video_url">
              <el-input v-model="editForm.video_url" placeholder="可选" />
            </el-form-item>
            <el-form-item label="帖子状态" prop="post_status">
              <el-input v-model="editForm.post_status" placeholder="如：寻找中、已找到、已关闭" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <h4>宠物信息</h4>
            <el-form-item label="宠物名字" prop="pet.name">
              <el-input v-model="editForm.pet.name" />
            </el-form-item>
            <el-form-item label="物种" prop="pet.species">
              <el-input v-model="editForm.pet.species" placeholder="如：狗、猫、兔子等" />
            </el-form-item>
            <el-form-item label="品种" prop="pet.breed">
              <el-input v-model="editForm.pet.breed" />
            </el-form-item>
            <el-form-item label="颜色" prop="pet.color">
              <el-input v-model="editForm.pet.color" />
            </el-form-item>
            <el-form-item label="性别" prop="pet.gender">
              <el-input v-model="editForm.pet.gender" placeholder="如：雄性、雌性、未知" />
            </el-form-item>
            <el-form-item label="描述" prop="pet.description">
              <el-input
                v-model="editForm.pet.description"
                type="textarea"
                :rows="3"
                placeholder="宠物的详细描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="editLoading" @click="submitEdit">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, ArrowDown } from '@element-plus/icons-vue'
import { getAllPosts, reviewPost, updatePost, deletePost, type Post, type PostUpdateData } from '@/api/posts'
import { getFullImageUrl } from '@/utils/helpers'
import dayjs from 'dayjs'

const posts = ref<Post[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

const filters = reactive({
  admin_status: '',
  post_status: ''
})

const detailDialogVisible = ref(false)
const selectedPost = ref<Post | null>(null)

// 编辑相关变量
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editForm = ref<PostUpdateData & { pet: any }>({
  last_seen_location: '',
  last_seen_time: '',
  post_status: '',
  video_url: '',
  contact_info: '',
  pet: {
    name: '',
    species: '',
    breed: '',
    color: '',
    gender: '',
    description: ''
  }
})

// 编辑表单验证规则
const editRules = {
  last_seen_location: [
    { required: true, message: '请输入最后目击地点', trigger: 'blur' }
  ],
  last_seen_time: [
    { required: true, message: '请选择最后目击时间', trigger: 'change' }
  ],
  'pet.name': [
    { required: true, message: '请输入宠物名字', trigger: 'blur' }
  ],
  'pet.species': [
    { required: true, message: '请输入物种', trigger: 'blur' }
  ],
  'pet.breed': [
    { required: true, message: '请输入品种', trigger: 'blur' }
  ],
  'pet.color': [
    { required: true, message: '请输入颜色', trigger: 'blur' }
  ],
  'pet.gender': [
    { required: true, message: '请输入性别', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('MM-DD HH:mm')
}

// 获取帖子状态类型
const getPostStatusType = (status: string) => {
  const types: Record<string, string> = {
    searching: 'warning',
    found: 'success',
    closed: 'info'
  }
  return types[status] || ''
}

// 获取帖子状态文本
const getPostStatusText = (status: string) => {
  const texts: Record<string, string> = {
    searching: '寻找中',
    found: '已找到',
    closed: '已关闭'
  }
  return texts[status] || status
}

// 获取审核状态类型
const getAdminStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    approved: 'success',
    rejected: 'danger'
  }
  return types[status] || ''
}

// 获取审核状态文本
const getAdminStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true

  try {
    const params: any = {
      page: currentPage.value,
      limit: pageSize.value
    }

    if (filters.admin_status) {
      params.admin_status = filters.admin_status
    }
    if (filters.post_status) {
      params.post_status = filters.post_status
    }

    const response = await getAllPosts(params)

    posts.value = response.data
    total.value = response.pagination.totalItems

  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 查看帖子详情
const viewPost = (post: Post) => {
  selectedPost.value = post
  detailDialogVisible.value = true
}

// 处理下拉菜单命令
const handleCommand = async (command: string, post: Post) => {
  switch (command) {
    case 'approve':
      await approvePost(post)
      break
    case 'reject':
      await rejectPost(post)
      break
    case 'edit':
      editPost(post)
      break
    case 'delete':
      await deletePostConfirm(post)
      break
  }
}

// 通过审核
const approvePost = async (post: Post) => {
  try {
    await reviewPost(post.id, { admin_status: 'approved' })
    ElMessage.success('帖子审核通过')
    fetchPosts()
  } catch (error) {
    console.error('审核失败:', error)
  }
}

// 拒绝审核
const rejectPost = async (post: Post) => {
  try {
    await reviewPost(post.id, { admin_status: 'rejected' })
    ElMessage.success('帖子已拒绝')
    fetchPosts()
  } catch (error) {
    console.error('拒绝审核失败:', error)
  }
}

// 删除帖子确认
const deletePostConfirm = async (post: Post) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除帖子"${post.pet.name}"吗？此操作将同时删除该帖子下的所有线索信息，且无法恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        confirmButtonClass: 'el-button--danger'
      }
    )
    await deletePostAction(post)
  } catch (error) {
    // 用户取消删除
  }
}

// 执行删除帖子
const deletePostAction = async (post: Post) => {
  try {
    await deletePost(post.id)
    ElMessage.success('帖子删除成功')
    fetchPosts()
  } catch (error) {
    console.error('删除帖子失败:', error)
    ElMessage.error('删除帖子失败')
  }
}

// 编辑帖子
const editPost = (post: Post) => {
  selectedPost.value = post
  // 填充编辑表单
  editForm.value = {
    last_seen_location: post.last_seen_location,
    last_seen_time: post.last_seen_time,
    post_status: post.post_status,
    video_url: post.video_url || '',
    contact_info: post.contact_info || '',
    pet: {
      name: post.pet.name,
      species: post.pet.species,
      breed: post.pet.breed,
      color: post.pet.color,
      gender: post.pet.gender,
      description: post.pet.description || ''
    }
  }
  editDialogVisible.value = true
}

// 重置编辑表单
const resetEditForm = () => {
  editFormRef.value?.resetFields()
  editForm.value = {
    last_seen_location: '',
    last_seen_time: '',
    post_status: '',
    video_url: '',
    contact_info: '',
    pet: {
      name: '',
      species: '',
      breed: '',
      color: '',
      gender: '',
      description: ''
    }
  }
}

// 提交编辑
const submitEdit = async () => {
  if (!selectedPost.value) return

  try {
    await editFormRef.value.validate()
    editLoading.value = true

    await updatePost(selectedPost.value.id, editForm.value)

    ElMessage.success('帖子更新成功')
    editDialogVisible.value = false
    fetchPosts()

  } catch (error) {
    console.error('更新帖子失败:', error)
    ElMessage.error('更新帖子失败')
  } finally {
    editLoading.value = false
  }
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchPosts()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchPosts()
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.posts-management {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pet-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pet-photo {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  object-fit: cover;
}

.pet-name {
  font-weight: bold;
  margin-bottom: 2px;
}

.pet-details {
  font-size: 12px;
  color: #666;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.post-detail {
  padding: 10px 0;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin-bottom: 10px;
  color: #333;
  border-bottom: 1px solid #eee;
  padding-bottom: 5px;
}

.pet-detail {
  display: flex;
  gap: 15px;
}

.pet-detail-photo {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  object-fit: cover;
}

.pet-detail-info p {
  margin: 5px 0;
  line-height: 1.5;
}
</style>
